package org.example;

import com.mysql.cj.util.StringUtils;
import com.mysql.cj.xdevapi.Client;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.UUID;

public class TestServer {
    private static String PORT;
    private static String ADDRESS;

    public static void main(String[] args) throws IOException {
        proper();

        cennection();

    }

    private static void cennection() {
        while(true){
            try {
                // 创建ServerSocket并监听指定端口
                ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PORT));
                // 接受客户端连接请求
                Socket clientSocket = serverSocket.accept();
                InputStream inputStream = clientSocket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String request = reader.readLine();
                // 解析请求，提取要删除的文件名
                String[] requestParts = request.split(" ");
                String requestType = requestParts[0];
                String FileName = requestParts[1];
                System.out.println(requestType);

                if (requestType.equals("DELETE")) {
                    // 删除文件
                    deleteFile(FileName);
                    System.out.println("服务端成功删除文件: " + FileName);
                }else if(requestType.equals("UPLOAD")){
                    uploadFile(FileName,clientSocket);
                    System.out.println("服务端成功创建文件: " + FileName);
                }
                // 关闭连接
            clientSocket.close();
            serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    private static void uploadFile(String fileName, Socket clientSocket) throws Exception {


    }



    private static void deleteFile(String fileName) {
        String serverDirectory = ADDRESS;
        String serverFilePath = serverDirectory + "/" + fileName;

        try {
            // 在服务端删除相同的文件
            Path serverPath = Paths.get(serverFilePath);
            Files.deleteIfExists(serverPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void proper() throws IOException {
        //读取properties
        InputStream inputStream = Client.class.getClassLoader().getResourceAsStream("server.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        PORT = properties.getProperty("port");
        ADDRESS = properties.getProperty("address");
        inputStream.close();
    }


}
